
package unibz.cn.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.Timer;

import org.dom4j.Element;
import org.dom4j.Node;

import unibz.cn.logic.User;

public class MainWindow extends javax.swing.JFrame {

    public MainWindow(User aUser) {
    	initComponents(aUser);
    	refreshTweets();
    }
    
    /**
     * Refresh the tweets list
     */
    private void refreshTweets() {
    	try {
    		List list = aUser.getTweets();
    		if (tweetsTextArea.getText().equals("")) {
    			Iterator iter=list.iterator();
    			while(iter.hasNext()){
    				Node node=(Node)iter.next();
    				if (lastId.equals("")) {
    					lastId = node.selectSingleNode("id").getText();
    				}
    				Node textNode = node.selectSingleNode("text");
    				Node authorNode = node.selectSingleNode("user/name");
    				tweetsTextArea.append("\nTweet by: " +authorNode.getText() + "\n");
    				tweetsTextArea.append(textNode.getText()+ "\n");
    				tweetsTextArea.append(".............................................................................................." +
    					"........................................................................................\n");
    			}
    			tweetsTextArea.setCaretPosition(0);
    			
    		} else {
    			Iterator iter=list.iterator();
    			Node node = null;
    			String partialId = "";
    			while(iter.hasNext()){
    			node=(Node)iter.next();
    			if (!node.selectSingleNode("id").getText().equals(lastId)) {
    				if (partialId.equals("")) {
    					partialId = node.selectSingleNode("id").getText();
    				}
    				Node textNode = node.selectSingleNode("text");
    				Node authorNode = node.selectSingleNode("user/name");
    				tweetsTextArea.insert(".............................................................................................." +
        					"........................................................................................\n",0);
    				tweetsTextArea.insert(textNode.getText()+ "\n",0);
    				tweetsTextArea.insert("\nTweet by: " +authorNode.getText() + "\n",0);
    				tweetsTextArea.setCaretPosition(0);
    			} else break;
    			}
    			if (!partialId.equals("")) {
    				lastId = partialId;
    			}
    		}
		} catch (Exception e) {
			e.printStackTrace();
		} 	
    	
    }
    
    private void initComponents(final User aUser) {
    	
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        tweetsTextArea = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        writableTextArea = new javax.swing.JTextArea();
        followButton = new javax.swing.JButton();
        addButton = new javax.swing.JButton();
        logoutButton = new javax.swing.JButton();
        commentsLabel = new javax.swing.JLabel();
        timerLabel = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        jMenuBar1 = new javax.swing.JMenuBar();
        //jMenuBar1.setBackground(getBackground());
        fileMenu = new javax.swing.JMenu();
        quitMenuItem = new javax.swing.JMenuItem();
        this.aUser = aUser;
        lastId = "";

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("UniBz Twitter Client");
        setTitle("UniBz Twitter Client");
        tweetsTextArea.setColumns(20);
        tweetsTextArea.setRows(5);
        tweetsTextArea.setEditable(false);
        jScrollPane1.setViewportView(tweetsTextArea);

        writableTextArea.setColumns(20);
        writableTextArea.setRows(5);
        jScrollPane2.setViewportView(writableTextArea);

        followButton.setText("Follow/Unfollow");
        followButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                followButtonActionPerformed(evt);
            }
        });
        
        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        logoutButton.setText("Logout");
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutButtonActionPerformed(evt);
            }
        });

        commentsLabel.setText("Add a new Tweet");

        timerLabel.setText("Tweets");

        fileMenu.setText("File");
        jMenuBar1.add(fileMenu);
        quitMenuItem.setText("Quit");
        quitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quitMenuItemActionPerformed(evt);
            }
        });
        
        ActionListener taskPerformer = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                refreshTweets();
            }
        };
        timer = new Timer( 30000 , taskPerformer);
        timer.start();
        
        fileMenu.add(quitMenuItem);
        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 700, Short.MAX_VALUE)
                                .addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(8, 8, 8))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(timerLabel))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(commentsLabel))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(followButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 167, Short.MAX_VALUE)
                                .addComponent(logoutButton)
                                ))
                        .addContainerGap())
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(timerLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(commentsLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(logoutButton)
                    .addComponent(followButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getAccessibleContext().setAccessibleParent(this);

        pack();
        
    }// </editor-fold>

    private void followButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FollowWindow(aUser).setVisible(true);
            }
        });
    }
    
    private void logoutButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginWindow().setVisible(true);
            }
        });
    	aUser = null; 
    	this.dispose();
    	this.timer.stop();
    }
    
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	if (!writableTextArea.getText().equals("")) {
    		aUser.addTweet(writableTextArea.getText());
    		writableTextArea.setText("");
    		refreshTweets();
    	} else {
    		JOptionPane.showMessageDialog(null,"Empty Message", "Attention",JOptionPane.ERROR_MESSAGE);
    	}
    }
    
    private void quitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
    	System.exit(0);
    }

    // Variables declaration - do not modify
    private javax.swing.JButton followButton;
    private javax.swing.JButton addButton;
    private javax.swing.JButton logoutButton;
    private javax.swing.JLabel commentsLabel;
    private javax.swing.JLabel timerLabel;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem quitMenuItem;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextArea tweetsTextArea;
    private javax.swing.JTextArea writableTextArea;
    private Timer timer;
    public User aUser;
    private String lastId;
    // End of variables declaration

}

